﻿using Apps.BLL.Core;
using Apps.Common;
using Apps.IBLL.LMS;
using Apps.IDAL.LMS;
using Apps.Locale;
using Apps.Models;
using LinqToExcel;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace Apps.BLL.LMS
{
    public partial class LOG_LMSEXCHANGEBLL : Virtual_LOG_LMSEXCHANGEBLL, ILOG_LMSEXCHANGEBLL
    {
    }

    public class Virtual_LOG_LMSEXCHANGEBLL
    {
        [Dependency]
        public ILOG_LMSEXCHANGERepository m_Rep { get; set; }
        public void Dispose()
        {

        }
        #region  实现GetLMSEXCHANGEList
        public List<V_LOG_LMSEXCHANGE> GetLMSEXCHANGEList(ref GridPager pager, Expression<Func<V_LOG_LMSEXCHANGE, bool>> whereLambda)
        {
            using (DBContainer db = new DBContainer())
            {
                var queryData = db.V_LOG_LMSEXCHANGE.Where(whereLambda);
                pager.totalRows = queryData.Count();
                queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
                return queryData.ToList();
            }
        }
        #endregion

        #region 实现GetItem
        public virtual V_LOG_LMSEXCHANGE GetItem(Expression<Func<V_LOG_LMSEXCHANGE, bool>> whereLambda)
        {

            V_LOG_LMSEXCHANGE entity = m_Rep.GetItem(whereLambda);
            if (entity == null) return null;

            V_LOG_LMSEXCHANGE model = new V_LOG_LMSEXCHANGE();
            model.LOG_ID = entity.LOG_ID;
            model.BATCH_CODE_A = entity.BATCH_CODE_A;
            model.BATCH_CODE_B = entity.BATCH_CODE_B;
            model.OPERATE_CONTENT= entity.OPERATE_CONTENT;
            model.OPERATE_USER_ID = entity.OPERATE_USER_ID;
            model.TRUENAME = entity.TRUENAME;
            model.OPERATE_TIME = entity.OPERATE_TIME;           

            return model;
        }
        #endregion

        #region  实现GetPageList
        public virtual List<V_LOG_LMSEXCHANGE> GetPagerList(ref GridPager pager, Expression<Func<V_LOG_LMSEXCHANGE, bool>> whereLambda)
        {

            IQueryable<V_LOG_LMSEXCHANGE> queryData = m_Rep.GetList(whereLambda);

            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }

        public virtual List<V_LOG_LMSEXCHANGE> CreateModelList(ref IQueryable<V_LOG_LMSEXCHANGE> queryData)
        {

            List<V_LOG_LMSEXCHANGE> modelList = (from r in queryData
                                                select new V_LOG_LMSEXCHANGE
                                                {
                                                    LOG_ID = r.LOG_ID,
                                                    BATCH_CODE_A = r.BATCH_CODE_A,
                                                    BATCH_CODE_B = r.BATCH_CODE_B,
                                                    OPERATE_CONTENT = r.OPERATE_CONTENT,
                                                    OPERATE_USER_ID = r.OPERATE_USER_ID,
                                                    TRUENAME = r.TRUENAME,
                                                    OPERATE_TIME = r.OPERATE_TIME,                                                    

                                                }).ToList();

            return modelList;
        }
        #endregion

        #region 实现GetList
        public virtual List<V_LOG_LMSEXCHANGE> GetList(Expression<Func<V_LOG_LMSEXCHANGE, bool>> whereLambda)
        {

            IQueryable<V_LOG_LMSEXCHANGE> queryData = m_Rep.GetList(whereLambda);

            return CreateModelList(ref queryData);
        }

        public virtual List<V_LOG_LMSEXCHANGE> GetList(ref GridPager pager, string queryStr)
        {

            IQueryable<V_LOG_LMSEXCHANGE> queryData = null;
            if (!string.IsNullOrWhiteSpace(queryStr))
            {
                queryData = m_Rep.GetList(
                                a => a.LOG_ID.Contains(queryStr)
                                || a.OPERATE_CONTENT.Contains(queryStr)
                                
                                || a.OPERATE_USER_ID.Contains(queryStr)
                                || a.TRUENAME.Contains(queryStr)
                                

                                || a.BATCH_CODE_B.Contains(queryStr)
                                || a.BATCH_CODE_A.Contains(queryStr)

                                );
            }
            else
            {
                queryData = m_Rep.GetList();
            }
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }

        public virtual List<V_LOG_LMSEXCHANGE> GetListByParentId(ref GridPager pager, string queryStr, object parentId)
        {
            return new List<V_LOG_LMSEXCHANGE>();
        }
        #endregion

        #region 实现Create
        public virtual bool Create(ref ValidationErrors errors, V_LOG_LMSEXCHANGE model)
        {
            try
            {
                V_LOG_LMSEXCHANGE entity = m_Rep.GetById(model.LOG_ID);
                if (entity != null)
                {
                    errors.Add(Resource.PrimaryRepeat);
                    return false;
                }
                entity = new V_LOG_LMSEXCHANGE();
                entity.LOG_ID = model.LOG_ID;
                entity.BATCH_CODE_A = model.BATCH_CODE_A;
                entity.BATCH_CODE_B = model.BATCH_CODE_B;
                entity.OPERATE_CONTENT = model.OPERATE_CONTENT;
                entity.OPERATE_USER_ID = model.OPERATE_USER_ID;
                entity.TRUENAME = model.TRUENAME;
                entity.OPERATE_TIME = model.OPERATE_TIME;

                if (m_Rep.Create(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.InsertFail);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }
        #endregion

        #region  实现Deletes
        public virtual bool Deletes(ref ValidationErrors errors, Expression<Func<V_LOG_LMSEXCHANGE, bool>> whereLambda)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {

                    foreach (var entity in db.V_LOG_LMSEXCHANGE.Where(whereLambda))
                    {
                        db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
                    }

                    if (db.SaveChanges() > 0)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }

                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }
        #endregion

        #region 实现Delete
        public virtual bool Delete(ref ValidationErrors errors, object id)
        {
            try
            {
                if (m_Rep.Delete(id) == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Delete(ref ValidationErrors errors, object[] deleteCollection)
        {
            try
            {
                if (deleteCollection != null)
                {
                    using (TransactionScope transactionScope = new TransactionScope())
                    {
                        if (m_Rep.Delete(deleteCollection) == deleteCollection.Length)
                        {
                            transactionScope.Complete();
                            return true;
                        }
                        else
                        {
                            Transaction.Current.Rollback();
                            return false;
                        }
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }
        #endregion

        #region 实现Edit
        public virtual bool Edit(ref ValidationErrors errors, V_LOG_LMSEXCHANGE model)
        {
            try
            {
                V_LOG_LMSEXCHANGE entity = m_Rep.GetById(model.LOG_ID);
                if (entity == null)
                {
                    errors.Add(Resource.Disable);
                    return false;
                }
                entity = new V_LOG_LMSEXCHANGE();
                entity.LOG_ID = model.LOG_ID;
                entity.BATCH_CODE_A = model.BATCH_CODE_A;
                entity.BATCH_CODE_B = model.BATCH_CODE_B;
                entity.OPERATE_CONTENT = model.OPERATE_CONTENT;
                entity.OPERATE_USER_ID = model.OPERATE_USER_ID;
                entity.TRUENAME = model.TRUENAME;
                entity.OPERATE_TIME = model.OPERATE_TIME;

                if (m_Rep.Edit(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.NoDataChange);
                    return false;
                }

            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }
        #endregion

        #region
        public virtual V_LOG_LMSEXCHANGE GetById(object id)
        {
            if (IsExists(id))
            {
                V_LOG_LMSEXCHANGE entity = m_Rep.GetById(id);
                V_LOG_LMSEXCHANGE model = new V_LOG_LMSEXCHANGE();
                model.LOG_ID = entity.LOG_ID;
                model.BATCH_CODE_A = entity.BATCH_CODE_A;
                model.BATCH_CODE_B = entity.BATCH_CODE_B;
                model.OPERATE_CONTENT = entity.OPERATE_CONTENT;
                model.OPERATE_USER_ID = entity.OPERATE_USER_ID;
                model.TRUENAME = entity.TRUENAME;
                model.OPERATE_TIME = entity.OPERATE_TIME;

                return model;
            }
            else
            {
                return null;
            }
        }

        public virtual bool IsExists(object id)
        {
            return m_Rep.IsExist(id);
        }
        #endregion


        public virtual bool CheckImportData(string fileName, List<V_LOG_LMSEXCHANGE> list, ref ValidationErrors errors)
        {

            var targetFile = new FileInfo(fileName);

            if (!targetFile.Exists)
            {

                errors.Add("导入的数据文件不存在");
                return false;
            }

            var excelFile = new ExcelQueryFactory(fileName);

            //对应列头
            excelFile.AddMapping<V_LOG_LMSEXCHANGE>(x => x.LOG_ID, "LOG_ID");
            excelFile.AddMapping<V_LOG_LMSEXCHANGE>(x => x.BATCH_CODE_A, "BATCH_CODE_A");
            excelFile.AddMapping<V_LOG_LMSEXCHANGE>(x => x.BATCH_CODE_B, "BATCH_CODE_B");
            excelFile.AddMapping<V_LOG_LMSEXCHANGE>(x => x.OPERATE_CONTENT, "OPERATE_CONTENT");
            excelFile.AddMapping<V_LOG_LMSEXCHANGE>(x => x.OPERATE_USER_ID, "OPERATE_USER_ID");
            excelFile.AddMapping<V_LOG_LMSEXCHANGE>(x => x.TRUENAME, "TRUENAME");
            excelFile.AddMapping<V_LOG_LMSEXCHANGE>(x => x.OPERATE_TIME, "OPERATE_TIME");

            //SheetName
            var excelContent = excelFile.Worksheet<V_LOG_LMSEXCHANGE>(0);
            int rowIndex = 1;
            //检查数据正确性
            foreach (var row in excelContent)
            {
                var errorMessage = new StringBuilder();
                var entity = new V_LOG_LMSEXCHANGE();
                entity.LOG_ID = row.LOG_ID;
                entity.BATCH_CODE_A = row.BATCH_CODE_A;
                entity.BATCH_CODE_B = row.BATCH_CODE_B;
                entity.OPERATE_CONTENT = row.OPERATE_CONTENT;
                entity.OPERATE_USER_ID = row.OPERATE_USER_ID;
                entity.TRUENAME = row.TRUENAME;
                entity.OPERATE_TIME = row.OPERATE_TIME;

                //=============================================================================
                if (errorMessage.Length > 0)
                {
                    errors.Add(string.Format(
                        "第 {0} 列发现错误：{1}{2}",
                        rowIndex,
                        errorMessage,
                        "<br/>"));
                }
                list.Add(entity);
                rowIndex += 1;
            }
            if (errors.Count > 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        public virtual void SaveImportData(IEnumerable<V_LOG_LMSEXCHANGE> list)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    foreach (var model in list)
                    {
                        V_LOG_LMSEXCHANGE entity = new V_LOG_LMSEXCHANGE();
                        entity.LOG_ID = model.LOG_ID;
                        entity.BATCH_CODE_A = model.BATCH_CODE_A;
                        entity.BATCH_CODE_B = model.BATCH_CODE_B;
                        entity.OPERATE_CONTENT = model.OPERATE_CONTENT;
                        entity.OPERATE_USER_ID = model.OPERATE_USER_ID;
                        entity.TRUENAME = model.TRUENAME;
                        entity.OPERATE_TIME = model.OPERATE_TIME;

                        db.V_LOG_LMSEXCHANGE.Add(entity);
                    }
                    db.SaveChanges();
                }
            }
            catch
            {
                throw;
            }
        }

        // <summary>
        /// 拆分批次
        /// </summary>
        /// <param name="p_code">批次号</param>
        /// <param name="pu_code">上传批次号</param>
        /// <param name="p_ids">计量ID</param> 
        /// <returns></returns>
        public bool JL_CHANGE_CODE(ref ValidationErrors errors, string p_code, string pu_code, string p_ids)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    DbParameter[] par = {
                    db.CreateInParameter("P_CODE",DbType.AnsiString, p_code),
                    db.CreateInParameter("PU_CODE",DbType.AnsiString, pu_code),
                    db.CreateInParameter("P_STR",DbType.AnsiString, p_ids),
                    db.CreateInParameter("P_CHAR",DbType.AnsiString, ","),
                    db.CreateOutParameter("P_ERRCODE", DbType.AnsiString, 20),
                    db.CreateOutParameter("P_ERRINFO", DbType.AnsiString, 100)  };

                    var ret = db.ExecuteProduce("PCK_CARWEIGHT.CHANGE_CODE", par);
                    if (ret["P_ERRCODE"].ToString() != "0")
                    {
                        errors.Add(ret["P_ERRINFO"].ToString());
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        /// <summary>
        /// 删除拆分批次
        /// </summary>
        /// <param name="p_code">批次号</param>
        /// <returns></returns>
        public bool JL_DELETE_CODE(ref ValidationErrors errors, string p_code)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    DbParameter[] pars = {
                    db.CreateInParameter("P_CODE",DbType.AnsiString, p_code),
                    db.CreateOutParameter("P_ERRCODE", DbType.AnsiString, 20),
                    db.CreateOutParameter("P_ERRINFO", DbType.AnsiString, 100) };

                    var ret = db.ExecuteProduce("PCK_CARWEIGHT.DELETE_CODE", pars);
                    if (ret["P_ERRCODE"].ToString() != "0")
                    {
                        errors.Add(ret["P_ERRINFO"].ToString());
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }







    }
}
